import {useLocation, useRoutes, Navigate} from "react-router-dom";
import router, {IRouter} from "./route";
import react from "react";
import {AuthRoute} from './AuthRoute.tsx'

function SetTitle({children, title}: { children: react.ReactElement, title: string }) {
    const location = useLocation()
    document.title = title
    if (location.pathname === '/')
        return <Navigate to="/home" replace/>
    else
        return <>{children}</>
}

function routerConfig(arr: IRouter[], isChildren: boolean = false, parentIsNoAuth: boolean = false): IRouter[] {
    return arr.map(item => {
        let element = item.element
        // 如果当前路由不需要验证权限
        if (item.isNoAuth) {
            element = <SetTitle title={item.title}>{item.element}</SetTitle>
        } else {
            // 如果需要验证权限（两种情况）
            // 如果当前是儿子路由单独判断
            if (isChildren) {
                // 如果父级不需要验证权限，那儿子就要加上验证
                if (parentIsNoAuth) {
                    element = <AuthRoute><SetTitle title={item.title}>{item.element}</SetTitle></AuthRoute>
                } else {
                    // 如果父亲需要验证权限，子级不需要验证权限
                    element = <SetTitle title={item.title}>{item.element}</SetTitle>
                }
            } else {
                // 2. 如果当前是父亲路由直接加上验证
                element = <AuthRoute><SetTitle title={item.title}>{item.element}</SetTitle></AuthRoute>
            }
        }
        return {
            ...item,
            element: element,
            children: item.children && item.children.length > 0 ? routerConfig(item.children, true, item.isNoAuth) : undefined
        }
    })
}

function Router() {
    console.log(routerConfig(router)[0].element)
    const routerTab = useRoutes(routerConfig(router)); //注册前端路由表
    return <>{routerTab}</>;
}

export default Router;
